package com.nantian.security.service;

import com.nantian.security.JwtUser;
import com.nantian.security.JwtUserFactory;
import com.nantian.security.repository.UserRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.nantian.model.security.User;

/**
 * Created by huozongsheng on 20.03.16.
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    private final Log logger = LogFactory.getLog(this.getClass());

    User userInfo = new User();
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user;

        if (username.contains("{{phoneNum}}")){
            logger.info("手机登录");
            user = userRepository.findByPhoneNum(username.replace("{{phoneNum}}",""));
            user.setUsername(username);
            user.setPassword(user.getCONFIRMCODE());
            userInfo = user;
        }
        else if (username.contains("{{userName}}")){
            logger.info("账号密码登录");
            user = userRepository.findByUsername(username.replace("{{userName}}",""));
            userInfo = user;
        }
        else {
            logger.debug("其他");
            user = userRepository.findByUsername(username);
        }
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            JwtUser jwtUser = JwtUserFactory.create(user);
            return jwtUser;
        }
    }
}
